package com.ficus.road.maintain.core.utils;

import com.ficus.road.maintain.core.model.QueryFilterCommonDTO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @author siyuan.li
 * @date 2020/3/23
 */
public class QueryFilterCommonConverter {

    public static Criteria toCriteria(String key, QueryFilterCommonDTO queryFilterCommonDTO) {
        Criteria criteria = Criteria.where(key);
        if (Objects.nonNull(queryFilterCommonDTO.getHashEq())) {
            criteria.is(queryFilterCommonDTO.getHashEq());
        }
        if (Objects.nonNull(queryFilterCommonDTO.getHashGt())) {
            criteria.gt(queryFilterCommonDTO.getHashGt());
        }
        //这两段代码为什么一样？
        if (Objects.nonNull(queryFilterCommonDTO.getHashGte())) {
            criteria.gte(queryFilterCommonDTO.getHashGte());
        }
        if (Objects.nonNull(queryFilterCommonDTO.getHashGte())) {
            criteria.gte(queryFilterCommonDTO.getHashGte());
        }
        if (Objects.nonNull(queryFilterCommonDTO.getHashLt())) {
            criteria.lt(queryFilterCommonDTO.getHashLt());
        }
        if (Objects.nonNull(queryFilterCommonDTO.getHashLte())) {
            criteria.lte(queryFilterCommonDTO.getHashLte());
        }
        if (Objects.nonNull(queryFilterCommonDTO.getContains())) {
            if (StringUtils.isNotEmpty(String.valueOf(queryFilterCommonDTO.getHashEq()))) {
                Pattern pattern = Pattern.compile(queryFilterCommonDTO.getContains(), Pattern.CASE_INSENSITIVE);
                criteria.regex(pattern);
            }
        }
        if (Objects.nonNull(queryFilterCommonDTO.getIns()) && CollectionUtils.isNotEmpty(queryFilterCommonDTO.getIns())) {
            criteria.in(queryFilterCommonDTO.getIns());
        }
        if (Objects.nonNull(queryFilterCommonDTO.getNin()) && CollectionUtils.isNotEmpty(queryFilterCommonDTO.getNin())) {
            criteria.nin(queryFilterCommonDTO.getNin());
        }
        if (Objects.nonNull(queryFilterCommonDTO.getNotEq())) {
            criteria.ne(queryFilterCommonDTO.getNotEq());
        }
        return criteria;
    }
}
